import {
    createRouter,
    createWebHashHistory
} from 'vue-router'

import Admin from "~/layouts/admin.vue"
import Login from '~/pages/login.vue'
import NotFound from '~/pages/404.vue'
import GoodList from '~/pages/goods/list.vue'
import MyManagerList from '~/pages/myManager/list.vue'
import MyDatasourceList from '~/pages/myDatasource/list.vue'
import MySearchManagerList from '~/pages/mySearchManager/list.vue'
import MyNoticeBoard from '~/pages/myNoticeBoard/list.vue'
import CategoryList from '~/pages/category/list.vue'
import UserList from '~/pages/user/list.vue'
import OrderList from '~/pages/order/list.vue'
import CommentList from '~/pages/comment/list.vue'


const routes = [
    {
        path: "/",
        name: "admin",
        component: Admin,
    },
    {
        path: "/login",
        component: Login,
        meta: {
            title: "登录页"
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound
    }
]
//动态路由，用于匹配菜单动态添加路由
const asyncRoutes = [{
    path: "/",
    component: GoodList,
    name: "/",
    meta: {
        title: "首页"
    }
},
{
    path: "/manager/list",
    component: MyManagerList,
    name: "/manager/list",
    meta: {
        title: "账号管理"
    }
},
{
    path: "/datasource/approve/list",
    name: "/datasource/approve/list",
    component: MyDatasourceList,
    meta: {
        title: "数据源审核"
    }
},
{
    path: "/datasource/search/list",
    name: "/datasource/search/list",
    component: MySearchManagerList,
    meta: {
        title: "搜索管理"
    }
},
{
    path: "/noticeBoard/setting",
    name: "/noticeBoard/setting",
    component: MyNoticeBoard,
    meta: {
        title: "公告栏管理"
    }
},
{
    path: "/user/setting",
    name: "/user/setting",
    component: CommentList,
    meta: {
        title: "账号维护"
    }
},
]

export const router = createRouter({
    history: createWebHashHistory(),
    routes
})

//动态添加路由
export function addRoutes(menus) {
    let hasNewRoutes = false
    const findAndAddRoutesByMenus = (arr) => {
        arr.forEach(e => {
            let item = asyncRoutes.find(o => o.path == e.frontPath)
            if (item && !router.hasRoute(item.path)) {
                router.addRoute("admin", item)
                hasNewRoutes = true
            }
            if (e.child && e.child.length > 0) {
                findAndAddRoutesByMenus(e.child)
            }
        })
    }
    findAndAddRoutesByMenus(menus)
    return hasNewRoutes
}